import os
import sys
from pathlib import Path
from typing import List, Optional, Any
from .logger import logger
from .config import config
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

def init_directories() -> bool:
    """初始化必要的目录结构"""
    try:
        # 创建基本目录
        directories = [
            'videos',    # 视频存储目录
            'temp',      # 临时文件目录
            'logs',      # 日志目录
            'config',    # 配置文件目录
            'cache',     # 缓存目录
            'drivers'    # 驱动程序目录
        ]
        
        for dir_name in directories:
            os.makedirs(dir_name, exist_ok=True)
            logger.info(f"创建目录: {dir_name}")
            
        return True
    except Exception as e:
        logger.error(f"创建目录结构失败: {str(e)}")
        return False

def init_config() -> bool:
    """初始化配置文件"""
    try:
        # 检查配置文件是否存在
        if not os.path.exists('config/settings.json'):
            # 使用默认配置创建配置文件
            config.save_config()
            logger.info("创建默认配置文件")
        return True
    except Exception as e:
        logger.error(f"初始化配置文件失败: {str(e)}")
        return False

def cleanup_temp() -> bool:
    """清理临时文件"""
    try:
        temp_dir = Path('temp')
        if temp_dir.exists():
            for file in temp_dir.glob('*'):
                try:
                    file.unlink()
                    logger.debug(f"删除临时文件: {file}")
                except Exception as e:
                    logger.warning(f"删除临时文件失败: {file} - {str(e)}")
        return True
    except Exception as e:
        logger.error(f"清理临时文件失败: {str(e)}")
        return False

def check_dependencies() -> List[str]:
    """检查依赖项"""
    missing_deps = []
    required_deps = [
        ('PyQt5', 'PyQt5'),
        ('cv2', 'opencv-python'),
        ('numpy', 'numpy'),
        ('selenium', 'selenium'),
        ('requests', 'requests')
    ]
    
    for module_name, package_name in required_deps:
        try:
            __import__(module_name)
        except ImportError:
            missing_deps.append(package_name)
    
    return missing_deps

def check_system_requirements() -> List[str]:
    """检查系统要求"""
    issues = []
    
    # 检查Python版本
    python_version = sys.version_info
    if python_version.major < 3 or (python_version.major == 3 and python_version.minor < 8):
        issues.append("需要Python 3.8或更高版本")
    
    # 检查操作系统
    if sys.platform not in ['win32', 'linux', 'darwin']:
        issues.append("不支持的操作系统")
    
    # 暂时跳过Chrome浏览器检查
    # TODO: 在实际需要使用浏览器功能时再进行检查
    pass
    
    return issues

def initialize_app() -> bool:
    """应用程序初始化"""
    try:
        # 检查系统要求
        system_issues = check_system_requirements()
        if system_issues:
            for issue in system_issues:
                logger.error(f"系统要求检查失败: {issue}")
            return False
        
        # 检查依赖项
        missing_deps = check_dependencies()
        if missing_deps:
            logger.error(f"缺少依赖项: {', '.join(missing_deps)}")
            logger.error("请运行: pip install -r requirements.txt")
            return False
        
        # 初始化目录结构
        if not init_directories():
            raise Exception("初始化目录结构失败")
            
        # 初始化配置文件
        if not init_config():
            raise Exception("初始化配置文件失败")
            
        # 清理临时文件
        if not cleanup_temp():
            logger.warning("清理临时文件失败")
            
        logger.info("应用程序初始化完成")
        return True
        
    except Exception as e:
        logger.error(f"应用程序初始化失败: {str(e)}")
        return False

# 导出便捷函数
def init() -> bool:
    return initialize_app()

def check_deps() -> List[str]:
    return check_dependencies()

def check_system() -> List[str]:
    return check_system_requirements()

def clean_temp() -> bool:
    return cleanup_temp()
